package cn._2dland.net
{
	import flash.events.ErrorEvent;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;

	[Event(name="complete", type="flash.events.Event")]
	[Event(name="error", type="flash.events.ErrorEvent")]

	public class VideoInfoLoader extends EventDispatcher
	{
		public static const INFO_URL:String = "/watch/player/";
		public static const FULL_INFO_URL:String = "http://www.2dland.cn/watch/player/";

		private var _loader:URLLoader;
		private var _partLoader:PartLoader;

		private var _parts:XMLList;
		private var _infos:Array;
		private var _partIndex:int;

		public function VideoInfoLoader() {
			super(null);

			_loader = new URLLoader();
			_loader.addEventListener(Event.COMPLETE, loadCompleteHandler);
			_loader.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
		}

		public function load(dir:String, vid:String, remote:Boolean=false):void {
			var infoUrl:String = remote ? FULL_INFO_URL : INFO_URL;
			
			infoUrl += dir + "/" + vid + ".xml?baka=" + Math.random();
			_loader.load(new URLRequest(infoUrl));
		}

		public function get infos():Array {
			return _infos;
		}

		private function loadPart(index:int):void {
			var partXml:XML = _parts[index] as XML;

			_partLoader = PartLoaderFactory.createPartLoader(partXml.@type);
			_partLoader.addEventListener(Event.COMPLETE, partCompleteHandler); 
			_partLoader.load(partXml);
		}

		protected function loadCompleteHandler(e:Event):void {
			var xmlData:String = new String(_loader.data);
			if(_loader.data == null || xmlData.length == 0){
				dispatchEvent(new ErrorEvent(ErrorEvent.ERROR));
				return;
			}

			var infoXML:XML = new XML(_loader.data);
			_parts = infoXML.part;
			_infos = new Array();

			_partIndex = 0;
			loadPart(_partIndex ++);
		}

		protected function ioErrorHandler(e:IOErrorEvent):void {
			dispatchEvent(new ErrorEvent(ErrorEvent.ERROR));
			return;
		}

		protected function partCompleteHandler(e:Event):void {
			_infos = _infos.concat(_partLoader.infos);
			_partLoader.release();

			if(_partIndex == _parts.length())
				dispatchEvent(new Event(Event.COMPLETE));
			else
				loadPart(_partIndex ++);
			
		}
	}
}